<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="40%"
    :before-close="handleClose"
  >
    <div class="class-dialog">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            placeholder="输入分类名称"
            style="width: 100%"
            v-model="ruleForm.name"
          />
        </el-form-item>
        <el-form-item label="上级分类" prop="pid">
          <el-tree-select
            default-expand-all
            node-key="id"
            filterable
            v-model="ruleForm.pid"
            :data="treeData"
            check-strictly
            clearable
            :render-after-expand="false"
            :props="{
              label: 'name',
              children: 'sub',
            }"
            style="width: 100% !important"
            placeholder="选择上级菜单"
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group
            v-model="ruleForm.status"
            :disabled="ruleForm.id ? true : false"
          >
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input
            placeholder="排序"
            style="width: 100%"
            v-model="ruleForm.sort"
          />
        </el-form-item>
        <div v-loading="loading" element-loading-text="上传中...">
          <el-form-item label="分类封面图" style="width: 100%">
            <div class="img-box" v-for="(item, i) in coverImgList" :key="i">
              <img :src="item.url" alt="" />

              <div class="occlusion">
                <el-icon class="del" @click="coverRemove(i)">
                  <IEpDelete />
                </el-icon>
              </div>
            </div>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :show-file-list="false"
              :file-list="coverImgList"
              :on-change="onChange"
            >
              <el-icon>
                <IEpPlus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <div v-loading="loading2" element-loading-text="上传中...">
          <el-form-item label="分类图标" style="width: 100%">
            <div class="img-box" v-for="(item, i) in logoImgList" :key="i">
              <img :src="item.url" alt="" />

              <div class="occlusion">
                <el-icon class="del" @click="logoRemove(i)">
                  <IEpDelete />
                </el-icon>
              </div>
            </div>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :show-file-list="false"
              :file-list="logoImgList"
              :on-change="onChangeLogo"
            >
              <el-icon>
                <IEpPlus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="分类描述" prop="remark" style="width: 100%">
            <el-input
              placeholder="描述"
              style="width: 100%"
              type="textarea"
              :row="2"
              v-model="ruleForm.remark"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { addApi, saveApi } from "@/plugins/api/shopping/class";
import { uploadImgApi } from "@/plugins/api/upload";
const props = defineProps({
  treeData: {
    type: Array,
    default: [],
  },
});
let ruleForm = ref({});
let rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  logoImgList.value = [];
  coverImgList.value = [];
  if (type == "add") {
    ruleForm.value = {};
    ruleForm.value.status = 1;
    title.value = "新增";
  } else {
    title.value = "编辑";
    ruleForm.value = Object.assign({}, row);
    if (row.cover) {
      coverImgList.value = [
        {
          url: import.meta.env.VITE_APP_BASE_API + row.cover,
        },
      ];
    }
    if (row.logo) {
      logoImgList.value = [
        {
          url: import.meta.env.VITE_APP_BASE_API + row.logo,
        },
      ];
    }
  }

  dialogVisible.value = true;
}
// 上传图片（大）
let coverImgList = ref([]);
let loading = ref(false);
function onChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  loading.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };

      if (coverImgList.value.length > 0) {
        coverImgList.value = [];
        coverImgList.value.push(obj);
      } else {
        coverImgList.value.push(obj);
      }
      ruleForm.value.cover = data.file_url;
      loading.value = false;

      //
    })
    .catch(() => {
      loading.value = false;
    });
}

function coverRemove(index) {
  coverImgList.value.splice(index, 1);
  ruleForm.value.cover = "";
}
// 上传图片（小）
let logoImgList = ref([]);
let loading2 = ref(false);
function onChangeLogo(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  loading2.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };

      if (logoImgList.value.length > 0) {
        logoImgList.value = [];
        logoImgList.value.push(obj);
      } else {
        logoImgList.value.push(obj);
      }
      ruleForm.value.logo = data.file_url;
      loading2.value = false;

      //
    })
    .catch(() => {
      loading2.value = false;
    });
}

function logoRemove(index) {
  logoImgList.value.splice(index, 1);
  ruleForm.value.logo = "";
}

const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (!ruleForm.value.id) {
        addApi(ruleForm.value).then((data) => {
          ElMessage.success("新增成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      } else {
        saveApi(ruleForm.value).then((data) => {
          ElMessage.success("修改成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      }
    }
  });
}

onMounted(() => {});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.class-dialog {
  :deep(.el-form-item) {
    width: 50%;
    margin-right: 0;
    padding-right: 10px;
    box-sizing: border-box;
    .el-input {
      width: 100%;
    }
  }

  .img-box {
    display: inline-block;
    margin-right: 5px;
    // margin-bottom: 10px;
    width: 148px;
    position: relative;

    img {
      width: 100%;
      height: 140px;
      object-fit: cover;
    }

    .occlusion {
      display: none;
      width: 100%;
      height: 140px;
      background: #9e9c9c75;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
      text-align: center;

      .del {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 148px;
        color: #464444;
        cursor: pointer;
        font-size: large;

        &:hover {
          color: rgb(130, 131, 133);
        }
      }
    }

    &:hover {
      .occlusion {
        display: block;
      }
    }
  }
}
</style>
